/*
 * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.registry.lifecycle.accenture.sample.utils;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.common.eventing.NotificationService;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.extensions.utils.CommonUtil;
import org.wso2.carbon.registry.lifecycle.accenture.sample.ServiceRequestLifeCycle;
import org.wso2.carbon.utils.ConfigurationContextService;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;

public class Utils {
    private static final Log log = LogFactory.getLog(Utils.class);

    private static RegistryService registryService;

    private static NotificationService registryNotificationService;

    private static String defaultNotificationServiceURL;

    private static String remoteTopicHeaderName;

    private static String remoteTopicHeaderNS;

    private static String remoteSubscriptionStoreContext;

    private static ConfigurationContextService configurationContextService;

    public static void createSubscriptionResource(Registry registry, String destinationAddress) {
        //Here we create all the subscription paths.
        ////
        Resource r1 = null;
        try {
            r1 = registry.newResource();
        } catch (RegistryException e) {
            e.printStackTrace();
        }
        byte[] r1content = "R1 content".getBytes();
        try {
            r1.setContent(r1content);
        } catch (RegistryException e) {
            e.printStackTrace();
        }
        try {
            log.info("Subscription path was set to :" + destinationAddress);
            registry.put(destinationAddress, r1);
        } catch (RegistryException e) {
            e.printStackTrace();
        }
    }

    public static String getServiceNameFromResource(Resource resource) throws RegistryException {
        Object resourceContent = null;
        try {
            resourceContent = resource.getContent();
        } catch (RegistryException e) {
            String msg = "Error in getting content from resource: " + resource.getPath();

            log.error(msg);
            throw new RegistryException(msg, e);
        }
        OMElement serviceInfoElement;
        String originalServicePath = resource.getPath();
        String serviceInfo;
        if (resourceContent instanceof String) {
            serviceInfo = (String) resourceContent;
        } else {
            serviceInfo = new String((byte[]) resourceContent);
        }

        try {
            XMLStreamReader reader = XMLInputFactory.newInstance().
                    createXMLStreamReader(new StringReader(serviceInfo));
            StAXOMBuilder builder = new StAXOMBuilder(reader);
            serviceInfoElement = builder.getDocumentElement();
        } catch (Exception e) {
            String msg = "Error in parsing the service content of the service. " +
                         "The requested path to store the service: " + originalServicePath + ".";
            log.error(msg);
            throw new RegistryException(msg, e);
        }

        // derive the service path that the service should be saved.
        return CommonUtil.getServiceName(serviceInfoElement);
    }

    @Deprecated
    public static String getSubscriptionPath (String state, String service) {
        return ServiceRequestLifeCycle.REGISTRY_NOTIFICATION_PATH + state + "-" + service;
    }

    /**
     * This generates a subscription path from the user email.
     * This replaces "@" in email to "_", to be compatible with name standard in G-Reg.
     * @param userEmail
     * @return
     */
    public static String getSubscriptionPath (String userEmail) {
        return ServiceRequestLifeCycle.REGISTRY_NOTIFICATION_PATH + userEmail.replaceAll("@", "_");
    }

    public static synchronized void setRegistryService(RegistryService service) {
        registryService = service;
    }

    public static synchronized RegistryService getRegistryService() {
        return registryService;
    }

    public static String getDefaultNotificationServiceURL() {
        return defaultNotificationServiceURL;
    }

    public static void setDefaultNotificationServiceURL(String defaultNotificationServiceURL) {
        Utils.defaultNotificationServiceURL = defaultNotificationServiceURL;
    }

    public static String getRemoteTopicHeaderName() {
        return remoteTopicHeaderName;
    }

    public static void setRemoteTopicHeaderName(String remoteTopicHeaderName) {
        Utils.remoteTopicHeaderName = remoteTopicHeaderName;
    }

    public static String getRemoteTopicHeaderNS() {
        return remoteTopicHeaderNS;
    }

    public static void setRemoteTopicHeaderNS(String remoteTopicHeaderNS) {
        Utils.remoteTopicHeaderNS = remoteTopicHeaderNS;
    }

    public static String getRemoteSubscriptionStoreContext() {
        return remoteSubscriptionStoreContext;
    }

    public static void setRemoteSubscriptionStoreContext(String remoteSubscriptionStoreContext) {
        Utils.remoteSubscriptionStoreContext = remoteSubscriptionStoreContext;
    }

    public static synchronized NotificationService getRegistryNotificationService() {
        return registryNotificationService;
    }

    public static synchronized void setRegistryNotificationService(NotificationService registryNotificationService) {
        Utils.registryNotificationService = registryNotificationService;
    }

    public static ConfigurationContextService getConfigurationContextService() {
        return configurationContextService;
    }

    public static void setConfigurationContextService(ConfigurationContextService configurationContextService) {
        Utils.configurationContextService = configurationContextService;
    }
}